package com.mandao.concurrency.example.singleton;

import com.mandao.concurrency.annotations.NotRecommend;
import com.mandao.concurrency.annotations.NotThreadSafe;
import com.mandao.concurrency.annotations.ThreadSafe;

/**
 *  懒汉式  双重锁机制
 */
@NotThreadSafe
public class SingletonExample4 {
    private SingletonExample4(){}

    private static SingletonExample4 instance = null;

    /**
     *
     *  cpu的工作流程
     *    1  memory = allocate() 分配对象的内存空间
     *    2  ctorInstance() 初始化对象
     *    3  instance =  memory 设置instance指向刚分配的内存空间
     *
     *   线程不安全的原因
     *   JVM 和cpu优化 发生了指令重排 1 3 2
     */
    public static SingletonExample4 getInstance(){
        if (null == instance){
            synchronized (SingletonExample4.class){
                if (null == instance){
                    instance = new SingletonExample4();
                }
            }
        }
        return instance;
    }
}
